package com.vision.web.controller;

import com.vision.cache.RunTimeVideoCache;
import com.vision.cache.VideoCache;
import com.vision.util.http.HttpRequestDao;
import com.vision.web.HttpConvert;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @version 1.0
 * @项目名称：
 * @类名称： IndexController.java
 * @类描述：
 * @创建人：zc
 * @创建时间：
 * @修改人：
 * @修改时间：
 * @修改备注：
 */
@Controller
@RequestMapping("/")
public class IndexController {

    private final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private HttpRequestDao requestDao;

    @Resource
    private RunTimeVideoCache runTimeVideoCache;

    @Resource
    private VideoCache videoCache;

    @RequestMapping("/")
    public String video(Integer count, HttpServletRequest request, Model model) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("requestIP:{}", remoteAddr);
        List<String> some = runTimeVideoCache.getUrlChanged(count == null ? 5 : count);
        model.addAttribute("urls", some);
        return "video";
    }


    @RequestMapping("/fq")
    public String fqVideo(Integer count, HttpServletRequest request, Model model) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("requestIP:{}", remoteAddr);
        List<String> some = runTimeVideoCache.getUlrWithoutChange(count == null ? 5 : count);
        model.addAttribute("urls", some);
        return "video_fq";
    }

    @RequestMapping("/u")
    public String upCache() {
        runTimeVideoCache.updateCache();
        return "redirect:/";
    }

    @RequestMapping(value = "read.video", method = RequestMethod.GET)
    public void index(HttpServletRequest request, HttpServletResponse response, String url) {
        long time = System.currentTimeMillis();
        try (InputStream inputStream = HttpConvert.convertResponse(response, this.getResponse(HttpConvert.convertRequest(request, new HttpGet(), url)));
             ServletOutputStream outputStream = response.getOutputStream()) {
            logger.info("request url:{} used time:{}", url, System.currentTimeMillis() - time);
            if (inputStream != null) {
                byte[] content = new byte[1024];
                int b;
                while ((b = inputStream.read(content)) != -1) {
                    outputStream.write(content, 0, b);
                }
            }

        } catch (IOException e) {
        }
    }

    private CloseableHttpResponse getResponse(HttpRequestBase request) throws IOException {
        CloseableHttpResponse response = requestDao.getResponse(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            // 删除缓存数据
            videoCache.remove("tumblr:video:cache:https://vtt.tumblr.com" + request.getURI().getPath());
        }
        return response;
    }
}
